const api = require('../services/api');
const chapterHandler = require('../handlers/chapterHandler');
const config = require('../configs/config');
var xlsx = require('node-xlsx');
var fs = require('fs');

const process = async () => {

    let { response: { data: data } } = await api.getCourses();
    //find all course
    var courses = data.filter(x => x.content_type == "course").map(x => { return { id: x.content_id, title: x.title } });
    for (const course of courses) {
        console.log("==============================");
        console.log(course.title + " processing...");
        await processCourse(course);
    }
}

const processCourse = async (course) => {
    let { response: { data: [{ class_content: chapters }] } } = await api.getChaptersByCourseId(course.id);

    let index = 1;
    for (const item of chapters) {
        let filename = `0${index}-${item.title.replace("/", "").replace("/", "")}.xlsx`;
        console.log(filename + " processing...");
        const workbook = xlsx.parse('./' + filename);
        let questions = await chapterHandler.processChapter(item.content.id);
        let output = path.join(__dirname, `../output/${course.title}`);

        data.forEach((x, index) => {
            //题干     题型		选项A	选项B	选项C	选项D	选项E	选项F	选项G	选项H	 答案   解析	章节	难度
            const record = [x.QuestionText, x.QuestionType, x.OptionA, x.OptionB, x.OptionC, x.OptionD, x.OptionE, x.OptionF, "", "", x.Anwser, x.Analysis, "", x.Difficulty]
            excel.push(record);
        });
        await generateExcel(output, filename, questions);
        index++;
    }
}

const generateExcel = async (output, filename, questions) => {
    const workbook = xlsx.parse('./' + output + "/" + filename);
    const excel = [...workbook[0].data];
    questions.forEach((x, index) => {
        //题干     题型		选项A	选项B	选项C	选项D	选项E	选项F	选项G	选项H	 答案   解析	章节	难度
        const record = [x.QuestionText, x.QuestionType, x.OptionA, x.OptionB, x.OptionC, x.OptionD, x.OptionE, x.OptionF, "", "", x.Anwser, x.Analysis, "", x.Difficulty]
        excel.push(record);
    });
    fs.mkdir(output, { recursive: true }, (error) => {
        fs.writeFileSync(output + "\\" + filename, buffer, 'binary');
    });
}

module.exports = {
    process
}